package com.ayuan.blog.controller;

import com.alibaba.fastjson.JSON;
import com.ayuan.blog.bean.ArticleInfo;
import com.ayuan.blog.bean.CommonResponseBean;
import com.ayuan.blog.common.util.CookieUtils;
import com.ayuan.blog.domain.Account;
import com.ayuan.blog.domain.Tag;
import com.ayuan.blog.domain.User;
import com.ayuan.blog.domain.sch.ArticleSch;
import com.ayuan.blog.service.AccountService;
import com.ayuan.blog.service.UserService;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaozhu on 15/12/27.
 */
@Log4j2
@Controller
public class LoginController extends BaseController{

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login() {
        log.info("login get");
        ModelAndView view = new ModelAndView("/login");
        return view;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object doLogin(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam("name") String userName,
                          @RequestParam("psd") String password) {
        log.info("login post");
        try {
            Account account = accountService.checkAccountAndPassword(userName, password);
            if (null != account) {
                User user = userService.findUserByAccountId(account.getId());

//                request.getSession().setAttribute("userInfo" + account.getId(), user);
//                request.getSession().setAttribute("sessionId" + account.getId(), account.getAccount());
                stringRedisTemplate.opsForValue().set("userInfo" + account.getId(), JSON.toJSONString(user), 60 , TimeUnit.MINUTES);
                stringRedisTemplate.opsForValue().set("sessionId" + account.getId(), account.getAccount(), 60, TimeUnit.MINUTES);
                response.addCookie(new Cookie("sessionId", String.valueOf(account.getId())));
                Map<String, String> resultMap = new HashMap<String, String>();
                resultMap.put("userName", userName);
                return new CommonResponseBean<Object>(0, "login success", resultMap);
            } else {
                return new CommonResponseBean<Object>(1, "login fail", null);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new CommonResponseBean<Object>(1, "login fail " + e.getMessage(), null);
        }
    }

    @RequestMapping(value = "/isLogin", method = RequestMethod.POST)
    @ResponseBody
    public Object isLogin(HttpServletRequest request) {
        Cookie cookie = CookieUtils.getCookie(request, "sessionId");
        if (cookie == null) {
            log.info("cookie is null");
            return new CommonResponseBean<Object>(0, "", false);
        } else {
            String userName = (String) request.getSession().getAttribute("sessionId" + cookie.getValue());
            if (StringUtils.isNotEmpty(userName)) {
                log.info(userName + " login");
                return new CommonResponseBean<Object>(0, "", true);
            } else {
                log.info("session out of time");
                return new CommonResponseBean<Object>(0, "", false);
            }
        }
    }

    @RequestMapping(value = "/sessionOutOfTime")
    @ResponseBody
    public Object sessionOutOfTime() {
        return new CommonResponseBean<Object>(10, "login out of time", null);
    }

    @RequestMapping(value = "/accessDenied", method = RequestMethod.GET)
    public ModelAndView accessDenied() {
        ModelAndView view = new ModelAndView("/accessDenied");
        return view;
    }

    @RequestMapping(value = "/sessionTimeout", method = RequestMethod.GET)
    public ModelAndView sessionTimeout() {
        ModelAndView view = new ModelAndView("/sessionTimeout");
        return view;
    }

    @RequestMapping(value = "/loginFailure", method = RequestMethod.GET)
    public ModelAndView loginFailure() {
        ModelAndView view = new ModelAndView("/loginFailure");
        return view;
    }

    @RequestMapping(value = "/profile", method = RequestMethod.GET)
    public ModelAndView profile() {
        ModelAndView view = new ModelAndView("/profile");
        return view;
    }
}
